﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Code.BLL;
using Code.Models;
using QianBuo.Lottery.Web.Areas.Manage.Models;
using QianBuo.Lottery.Web.Models;
using QianBuo.Lottery.Web.Areas.Manage.Models.Lottery;
using QianBuo.Lottery.Web.Controllers;



namespace QianBuo.Lottery.Web.Areas.Manage.Controllers
{
    public class LotteryController : BaseController
    {

        #region 奖金\返点设置
        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult ConfigWinMoney(LotteryTypeType? id)
        {
            var model = new WinMoneySetModel();
            var LM = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort);
            model.Lotterys = new ModelNameValue<LotteryTypeType, string>(LM.Select(p => new NameValueItem<LotteryTypeType, string>(p.Key, p.Value.Name)));
            if (id.HasValue)
                model.LotteryID = id;
            else if (!id.HasValue && model.Lotterys.Count > 0)
                model.LotteryID = model.Lotterys.First().Key;
            else
                model.LotteryID = (LotteryTypeType)(-1);

            var PM = new PlayTypeOptionManage();
            model.Options = PM.GetUserOption_SetWithChild(null, (int)model.LotteryID.Value.GetDefaultLottery(), null, false).ToArray();
            model.ViewData = new ModelNameValue<string, object>();
            model.ViewData.Add("old", model.Options);
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult ConfigWinMoney(WinMoneySetModel model)
        {
            if (model == null || model.Options == null)
                return RedirectToAction("ConfigWinMoney");
            var PM = new PlayTypeOptionManage();
            PlayTypeOptionManage.WinMoneyOptionSetItem[] old = null;
            if (model.ViewData != null && model.ViewData.ContainsKey("old") && (old = model.ViewData["old"] as PlayTypeOptionManage.WinMoneyOptionSetItem[]) != null)
            {
                old.Each((p, i) =>
                {
                    //如果下标有改动测用此代码
                    //i=Array.FindIndex(model.Options, p1 => p1.Option.PlayTypeID == p.Option.PlayTypeID && p.Option.WinMoneyModelID == p.Option.WinMoneyModelID);
                    var item = model.Options[i];
                    item.LotteryName = p.LotteryName;
                    item.PlayName = p.PlayName;
                    item.PlayNames = p.PlayNames;
                    item.Option.LotteryID = p.Option.LotteryID;
                    item.Option.PlayTypeID = p.Option.PlayTypeID;
                    item.Option.PlayTypeListID = p.Option.PlayTypeListID;
                    item.Option.WinMoneyModelID = p.Option.WinMoneyModelID;

                    if (item.Option.WinMoney < 0)
                        ModelState.AddModelError(string.Format("Options[{0}].Option.WinMoney", i), ">=" + 0);
                    if (item.Option.BackMoneyRatio < 0)
                        ModelState.AddModelError(string.Format("Options[{0}].Option.BackMoneyRatio", i), ">=" + 0);

                    if (item.Option.BackMoneyToWinMoneyRatio < 0)
                        ModelState.AddModelError(string.Format("Options[{0}].Option.BackMoneyToWinMoneyRatio", i), ">=" + 0);
                    if (item.Option.MaxBackMoneyToWinMoney < 0)
                        ModelState.AddModelError(string.Format("Options[{0}].Option.MaxBackMoneyToWinMoney", i), ">=" + 0);
                });
            }
            else
                ModelState.AddModelError("Error", "缺少参数，请刷新页面！");

            if (ModelState.IsValid)
            {
                int rs = PM.SetUserOption(null, model.Options.Select(p => p.Option));
                if (rs < 0)
                    ViewData["msg"] = "操作失败！请稍后重试。".AlertOffPage("msg.value = '';", false);
                else
                    ViewData["msg"] = Url.Action("ConfigWinMoney", new { id = model.LotteryID }).Redirect("保存成功！");
            }


            return View(model);
        }

        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult ResetWinMoney()
        {
            var model = new ResetWinMoneyModel();
            model.WinModels = CacheManage.WinModel.Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name }).ToList();
            model.WinModels.Insert(0, new SelectListItem { Text = "所有模式", Value = "" });
            model.Lotters = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort).Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name }).ToList();
            model.Lotters.Insert(0, new SelectListItem { Text = "所有彩重", Value = "" });
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult ResetWinMoney(ResetWinMoneyModel model)
        {
            model.WinModels = CacheManage.WinModel.Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.WinModelID == p.Key }).ToList();
            model.WinModels.Insert(0, new SelectListItem { Text = "所有模式", Value = "" });
            model.Lotters = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort).Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name }).ToList();
            model.Lotters.Insert(0, new SelectListItem { Text = "所有彩重", Value = "" });
            if (ModelState.IsValid)
            {
                LotteryType? lottery = model.Lottery.HasValue ? (model.Lottery.Value.GetDefaultLottery()) as LotteryType? : null;
                var PM = new PlayTypeOptionManage();

                int rs = PM.ResetWinMoney(model.WinModelID, lottery, model.WinMoney, model.Ratio);
                if (rs > 0)
                    return Content("".Redirect("调整完成！"));
                else if (rs == 0)
                    return Content("".Redirect("无操作！"));
                else
                    ViewData["msg"] = "操作失败，请稍后再试！".AlertOffPage();
            }
            return View(model);
        }

        #endregion

        #region 彩种设置
        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult ConfigLottery()
        {
            LotteryManage LM = new LotteryManage();
            var ls = CacheManage.Lottery.Values.OrderBy(p => p.ID).OrderBy(p => p.Sort).Select(p => new LotterySetModel.LotteryModel
            {
                ID = p.ID,
                Name = p.Name,
                State = p.State == (short)LotteryState.Normal,
                AutoAddIssue = p.AutoAddIssue,
                ForwardEnd = p.ForwardEnd,
                OpenWinDelayTime = p.OpenWinDelayTime,
                OpenWinOverTime = p.OpenWinOverTime,
                Sort = p.Sort
            }).ToArray();
            LotterySetModel model = new LotterySetModel { Lotterys = ls };

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult ConfigLottery(LotterySetModel model)
        {
            if (model == null || model.Lotterys == null)
                return RedirectToAction("ConfigLottery");


            if (ModelState.IsValid)
            {
                var ups = model.Lotterys.ToNameValue(p => (object)new
                {
                    p.AutoAddIssue,
                    p.ForwardEnd,
                    p.OpenWinDelayTime,
                    p.OpenWinOverTime,
                    p.Sort,
                    State = p.State ? LotteryState.Normal : LotteryState.Locked
                }, p => (object)new { p.ID });

                LotteryManage LM = new LotteryManage();
                int rs = LM.Update(ups);
                if (rs < 0)
                    ViewData["msg"] = "保存失败，请稍后再试！".AlertOffPage();
                else
                {
                    CacheManage.IsLoadLottery = true;
                    return Content(Url.Action("ConfigLottery").Redirect("保存成功!"));
                }
            }

            return View(model);
        }



        #endregion


        #region 返点类型设置

        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult BackMoneyType()
        {
            var BM = new BackMoneyTypeManage();
            var model = new BackMoneyTypeModel
            {
                Types = BM.Select(s => s.Select(p => new BackMoneyTypeItem { ID = p.ID, Name = p.Name }).ToArray())
            };

            return View(model);
        }

        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult AddBackMoneyType(int? id, bool? n)
        {
            var BM = new BackMoneyTypeManage();
            var model = new BackMoneyTypeEditModel { N = n ?? false, ID = id };
            if (!model.N)
            {
                if (!model.ID.HasValue)
                    return RedirectToAction("BackMoneyType");
                var item = BM.Select(s => s.FirstOrDefault(p => p.ID == model.ID));
                if (item == null)
                    return RedirectToAction("BackMoneyType");
                model.Name = item.Name;
            }

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult AddBackMoneyType(BackMoneyTypeEditModel model)
        {
            if (!model.N && !model.ID.HasValue)
                return RedirectToAction("BackMoneyType");

            if (ModelState.IsValid)
            {
                var BM = new BackMoneyTypeManage();
                int rs = 0;
                if (model.N)
                    rs = BM.InsertData(model.Name);
                else
                    rs = BM.Edit(model.ID.Value, model.Name);
                if (rs > 0)
                    return Content(Url.Action("BackMoneyType").Redirect("操作成功"));
                else
                    ViewData["msg"] = "操作失败！".AlertOffPage();
            }
            return View(model);
        }

        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult DelBackMoneyType(int? id)
        {
            if (!id.HasValue)
                return RedirectToAction("BackMoneyType");

            var BM = new BackMoneyTypeManage();
            int rs = BM.Del(id.Value);
            string msg = "";
            if (rs > 0)
                msg = "删除成功！";
            else
                msg = "删除失败，请检查是否有玩法使用该返点类型！";
            return Content(Url.Action("BackMoneyType").Redirect(msg));

        }

        #endregion


        #region 玩法设置
        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult ConfigPlayType(LotteryType? id)
        {
            var lots = CacheManage.Lottery.OrderBy(p => p.Value.ID).OrderBy(p => p.Value.Sort);
            if (!id.HasValue && lots.Count() > 0)
                id = (LotteryType)lots.First().Value.ID;
            else if (!id.HasValue)
                id = (LotteryType)(-1);

            PlayTypeManage PM = new PlayTypeManage();

            var model = new PlayTypeSetModel()
            {
                Lottery = id.Value,
                Lotterys = new ModelNameValue<LotteryType, string>(lots.ToNameValue(p => p.Key, p => p.Value.Name)),
                PlayTypes = CacheManage.PlayType.Values.OrderBy(p => p.ID).OrderBy(p => p.Sort).Where(p => p.LotteryID == (int)id.Value)
                    .Select(p => new PlayTypeSetModel.PlayTypeModel
                    {
                        ID = p.ID,
                        Name = p.PlayTypeList.Name,
                        MaxBuyCount = p.MaxBuyCount,
                        MaxBuyMultiple = p.MaxBuyMultiple,
                        BuyNumbers = p.MaxBuyNumber.Split(',').Select(pp => new PlayTypeSetModel.BuyNumber { Len = (pp.IsInt() ? (object)int.Parse(pp) : null) as int? }).ToArray(),
                        State = p.State == (short)PlayTypeState.Normal,
                        Sort = p.Sort,
                        BackMoneyTypeID = Convert.ToInt32(p.BackMoneyTypeID),
                        RestrictiveNumber = p.RestrictiveNumber
                    }).ToArray()
            };
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult ConfigPlayType(PlayTypeSetModel model)
        {
            if (model == null || model.PlayTypes == null)
                return RedirectToAction("ConfigPltyType");

            var l = Code.BLL.Arithmetic.LotteryFactory.CreateLottery(model.Lottery);
            model.PlayTypes.Each((p, i) =>
            {
                var tp = l.GetPlayType((PlayType_E)CacheManage.PlayType[p.ID].PlayTypeListID);
                var s = string.IsNullOrEmpty(p.RestrictiveNumber) ? new string[0] : p.RestrictiveNumber.Split('|');
                foreach (var item in s)
                {
                    if (tp.RegistNum(item) == null)
                    {
                        ModelState.AddModelError(string.Format("PlayTypes[{0}].RestrictiveNumber", i), item);
                        break;
                    }
                }
            });
            if (ModelState.IsValid)
            {
                var ups = model.PlayTypes.ToNameValue(p => (object)new { p.MaxBuyCount, p.MaxBuyMultiple, p.BackMoneyTypeID, p.Sort, State = p.State ? PlayTypeState.Normal : PlayTypeState.Locked, MaxBuyNumber = string.Join(",", p.BuyNumbers.Select(pp => pp.Len.ToString()).ToArray()), p.RestrictiveNumber }, p => (object)new { p.ID });
                PlayTypeManage LM = new PlayTypeManage();
                int rs = LM.Update(ups);
                if (rs < 0)
                    ViewData["msg"] = "保存失败，请稍后再试！".AlertOffPage();
                else
                {
                    CacheManage.IsLoadPlayType = true;
                    string msg = string.Format("<script>alert('保存成功！');location.href='{0}'</script>", Url.Action("ConfigPlayType"));
                    return Content(msg);

                }
            }

            return View(model);
        }

        #endregion

        #region 开奖
        [Authorize(Roles = "Manager_Lottery_Open")]
        public ActionResult KaiJiang(LotteryType? id)
        {
            KaiJiamgModel model = new KaiJiamgModel();
            model.Lotterys = CacheManage.Lottery.OrderBy(p => p.Value.ID).OrderBy(p => p.Value.Sort).Select(p => new SelectListItem { Text = p.Value.Name, Value = p.Key.ToString() }).ToList();
            model.Lotterys.Insert(0, new SelectListItem { Text = "选择彩种", Value = "" });
            model.Lottery = id;
            if (model.Lottery.HasValue)
            {
                var CM = new CommenManage<Issue>();
                model.Issues = CM.Select(s => s.Where(p => p.LotteryID == (short)model.Lottery && p.State == (short)IssueState.Normal && p.EndTime < DateTime.Now))
                    .OrderByDescending(p => p.EndTime).ToArray().Select(p => new SelectListItem { Text = p.FormatIssueName, Value = p.ID.ToString() }).ToList();
                model.Issues.Insert(0, new SelectListItem { Text = "选择期号", Value = "" });
            }
            else
                model.Issues = new List<SelectListItem>() { new SelectListItem { Text = "选择期号", Value = "" } };

            return View(model);
        }

        [Authorize(Roles = "Manager_Lottery_Open")]
        public ActionResult KaiJiangIssue(LotteryType id)
        {
            var CM = new CommenManage<Issue>();
            var issues = CM.Select(s => s.Where(p => p.LotteryID == (short)id && p.State == (short)IssueState.Normal && p.EndTime < DateTime.Now))
                   .OrderByDescending(p => p.EndTime).ToArray().Select(p => new SelectListItem { Text = p.FormatIssueName, Value = p.ID.ToString() }).ToList();
            issues.Insert(0, new SelectListItem { Text = issues.Count == 0 ? "无未开奖期号" : "选择期号", Value = "" });
            return PartialView(issues);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Lottery_Open")]
        public ActionResult KaiJiang(KaiJiamgModel model)
        {
            model.Lotterys = CacheManage.Lottery.OrderBy(p => p.Value.ID).Select(p => new SelectListItem { Text = p.Value.Name, Value = p.Key.ToString() }).ToList();
            model.Lotterys.Add(new SelectListItem { Text = "选择彩种", Value = "" });
            model.Issues = new List<SelectListItem>() { new SelectListItem { Text = "选择期号", Value = "" } };
            if (ModelState.IsValid)
            {
                var l = CacheManage.Lottery[model.Lottery.Value];
                if (l == null)
                {
                    ModelState.AddModelError("Lottery", "不存在该彩种");
                }
                if (l.Name == "广东快乐十分")
                {
                    var list = model.OpenCode.Split(new string[] { ",", "," }, StringSplitOptions.RemoveEmptyEntries);


                    if (list.Length != 8)
                    {
                        ModelState.AddModelError("OpenCode", l.Name + " 开奖号码个数为 " + l.OpenCodeLength + " 位");
                    }
                }
                else
                {
                    if (model.OpenCode.Length != l.OpenCodeLength)
                        ModelState.AddModelError("OpenCode", l.Name + " 开奖号码个数为 " + l.OpenCodeLength + " 位");
                }
            }
            if (ModelState.IsValid)
            {
                SchemeManage SM = new SchemeManage();
                var issue = SM.Select<Issue, Issue>(s => s.FirstOrDefault(p => p.ID == model.IssueID));
                int rs = SM.Update<Issue>(new { State = (short)IssueState.Opened, OpenCode = model.OpenCode }, new { State = (short)IssueState.Normal, ID = model.IssueID });
                if (rs == 1)
                {
                    var states = new short[] { (short)SchemeState.Opened, (short)SchemeState.SysCancel, (short)SchemeState.UserCancel, (short)SchemeState.TimeOutCancel };
                    var schemes = SM.Select(s => s.Where(p => p.IssueID == model.IssueID && !states.Contains(p.State)).Select(p => new { p.ID, p.State })).ToArray();
                    int win = 0; int error = 0;
                    schemes.Each(p =>
                    {
                        try
                        {
                            rs = SM.BuJian(p.ID);
                            if (rs > 0)
                                win++;
                            else if (rs < 0)
                                error++;
                        }
                        catch { error++; }
                    });
                    if (schemes.Length > 0)
                        ViewData["msg"] = Url.Action("Index", "Scheme", Url.Route(new { serch = new { LotteryType = model.Lottery, IssueName = issue.FormatIssueName }, returnurl = Url.Action("KaiJiang", new { model.Lottery }), act = "KaiJiang", cont = "Lottery" })).Redirect(string.Format("{0} 第 {1} 期开奖结果:\\r\\n成功:{2} 个,失败:{3} 个，中奖方案:{4} 个",
                            model.Lottery.Value.GetName(), issue.FormatIssueName, schemes.Length - error, error, win));
                    else
                        ViewData["msg"] = Url.Action("KaiJiang", Url.Route(new { model.Lottery })).Redirect(string.Format("{0} 第 {1} 期开奖结果:\\r\\n成功:{2} 个,失败:{3} 个，中奖方案:{4} 个",
                            model.Lottery.Value.GetName(), issue.FormatIssueName, schemes.Length - error, error, win));
                }
                else
                {
                    if (issue == null)
                        ModelState.AddModelError("IssueID", "期号不存在");
                    else if (issue.State == (short)IssueState.Opened)
                        ModelState.AddModelError("IssueID", "该期已开奖");
                    else
                        ModelState.AddModelError("Error", "系统错误");
                }
            }

            return View(model);
        }

        #endregion

        #region 出票

        [Authorize(Roles = "Manager_Lottery_Open")]
        public ActionResult ChuPiao(LotteryType? id)
        {
            var model = new ChuPiaoModel();
            model.Lotterys = CacheManage.Lottery.OrderBy(p => p.Value.ID).Select(p => new SelectListItem { Text = p.Value.Name, Value = p.Key.ToString() }).ToList();
            model.Lotterys.Insert(0, new SelectListItem { Text = "选择彩种", Value = "" });
            model.Lottery = id;
            if (model.Lottery.HasValue)
            {
                var CM = new CommenManage<Issue>();
                var tmp = CM.Select<Scheme, IEnumerable<Issue>>(s => s.Where(p => p.Issue.EndTime < DateTime.Now && p.State == (short)SchemeState.Normal).GroupBy(p => p.Issue).Select(p => p.Key).OrderByDescending(p => p.EndTime));
                model.Issues = tmp.ToArray().Select(p => new SelectListItem { Text = p.FormatIssueName, Value = p.ID.ToString() }).ToList();
                model.Issues.Insert(0, new SelectListItem { Text = "选择期号", Value = "" });
            }
            else
                model.Issues = new List<SelectListItem>() { new SelectListItem { Text = "选择期号", Value = "" } };

            return View(model);
        }

        [Authorize(Roles = "Manager_Lottery_Open")]
        public ActionResult ChuPiaoIssue(LotteryType id)
        {
            var CM = new CommenManage<Issue>();
            var tmp = CM.Select<Scheme, IEnumerable<Issue>>(s => s.Where(p => p.LotteryID == (short)id && p.Issue.EndTime < DateTime.Now && p.State == (short)SchemeState.Normal).GroupBy(p => p.Issue).Select(p => p.Key).OrderByDescending(p => p.EndTime));
            var issues = tmp.ToArray().Select(p => new SelectListItem { Text = p.FormatIssueName, Value = p.ID.ToString() }).ToList();
            issues.Insert(0, new SelectListItem { Text = issues.Count == 0 ? "无未出票期号" : "选择期号", Value = "" });
            return PartialView("KaiJiangIssue", issues);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Lottery_Open")]
        public ActionResult ChuPiao(ChuPiaoModel model)
        {
            model.Lotterys = CacheManage.Lottery.OrderBy(p => p.Value.ID).Select(p => new SelectListItem { Text = p.Value.Name, Value = p.Key.ToString() }).ToList();
            model.Lotterys.Add(new SelectListItem { Text = "选择彩种", Value = "" });
            model.Issues = new List<SelectListItem>() { new SelectListItem { Text = "选择期号", Value = "" } };
            if (ModelState.IsValid)
            {
                var l = CacheManage.Lottery[model.Lottery.Value];
                if (l == null)
                {
                    ModelState.AddModelError("Lottery", "不存在该彩种");
                }
            }
            if (ModelState.IsValid)
            {
                SchemeManage SM = new SchemeManage();
                var issue = SM.Select<Issue, Issue>(s => s.FirstOrDefault(p => p.ID == model.IssueID));

                if (issue != null && issue.State == (short)IssueState.Normal)
                {
                    var schemes = SM.Select(s => s.Where(p => p.State == (short)SchemeState.Normal && p.IssueID == model.IssueID.Value).ToArray());
                    int rs; int error = 0;
                    schemes.Each(p =>
                    {
                        try
                        {
                            rs = SM.OutBill(p);

                            if (rs < 0)
                            {
                                error++;
                            }

                        }
                        catch { error++; }
                    });
                    if (schemes.Length > 0)
                        ViewData["msg"] = Url.Action("Index", "Scheme", Url.Route(new { serch = new { LotteryType = model.Lottery, IssueName = issue.FormatIssueName }, returnurl = Url.Action("ChuPiao", new { model.Lottery }), act = "ChuPiao", cont = "Lottery" })).Redirect(string.Format("{0} 第 {1} 出票奖结果:\\r\\n成功:{2} 个,失败:{3} 个，共:{4} 个",
                            model.Lottery.Value.GetName(), issue.FormatIssueName, schemes.Length - error, error, schemes.Length));
                    else
                        ViewData["msg"] = Url.Action("ChuPiao", Url.Route(new { model.Lottery })).Redirect(string.Format("{0} 第 {1} 期出票结果:\\r\\n成功:{2} 个,失败:{3} 个，共:{4} 个",
                            model.Lottery.Value.GetName(), issue.FormatIssueName, schemes.Length - error, error, schemes.Length));
                }
                else
                {
                    if (issue == null)
                        ModelState.AddModelError("IssueID", "期号不存在");
                    else if (issue.State == (short)IssueState.Opened)
                        ModelState.AddModelError("IssueID", "该期已开奖");
                    else
                        ModelState.AddModelError("Error", "系统错误");
                }
            }

            return View(model);
        }

        #endregion
    }
}
